package com.xunker.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunker.appointment.enums.AuthStatusEnum;
import com.xunker.appointment.exception.AppointmentException;
import com.xunker.appointment.model.patient.Patient;
import com.xunker.appointment.model.user.UserInfo;
import com.xunker.appointment.result.ResultCodeEnum;
import com.xunker.appointment.vo.user.UserAuthVo;
import com.xunker.helper.JwtHelper;
import com.xunker.user.mapper.UserInfoMapper;
import com.xunker.user.service.PatientService;
import com.xunker.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl  extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService{
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> loginUser(Map map) {
        //1.获取手机号和验证码
        //String phone=map.get("phone").toString();
        String email=map.get("email").toString();
        String code=map.get("code").toString();
        String status = map.get("status").toString();
        String token ="";
        String name=map.get("name").toString();
        String openid=map.get("openid").toString();
        Map userMap=new HashMap();
        //判断验证码
        //String phone_code = redisTemplate.opsForValue().get(phone);
        String email_code = redisTemplate.opsForValue().get(email);
        if(StringUtils.isEmpty(email_code)||!email_code.equals(code)){
            throw new AppointmentException(ResultCodeEnum.CODE_ERROR);
        }
        //2.判断是否合法
        if (StringUtils.isEmpty(email)||StringUtils.isEmpty(code)) {
            throw new AppointmentException(ResultCodeEnum.PARAM_ERROR);
        }
        //绑定手机号码
       /* UserInfo userInfo_p = null;
        if(!StringUtils.isEmpty(openid)) {
            userInfo_p = this.getByOpenid(openid);
            if(null != userInfo_p) {
                userInfo_p.setPhone(phone);
                this.updateById(userInfo_p);
            } else {
                throw new AppointmentException(ResultCodeEnum.DATA_ERROR);
            }
        }*/
        //3.绑定邮箱
        UserInfo userInfo_e = null;
        if(!StringUtils.isEmpty(openid)) {
            userInfo_e = this.getByOpenid(openid);
            if(null != userInfo_e) {
                userInfo_e.setPhone(email);
                this.updateById(userInfo_e);
            } else {
                throw new AppointmentException(ResultCodeEnum.DATA_ERROR);
            }
        }
        //4.判断是否是第一次登录
        //userInfo_e=null 说明邮箱直接登录
        if(null == userInfo_e) {
            //final UserInfo userInfo = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", phone));
            final UserInfo userInfo = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("email", email));
            if (userInfo==null){//第一次登录
                baseMapper.insert(new UserInfo(email, name, Integer.parseInt(status)));
            }else if (userInfo.getStatus()==0){
                throw new AppointmentException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
            }else if (StringUtils.isEmpty(userInfo.getName())){
                name=userInfo.getNickName();
            }else if(StringUtils.isEmpty(name)){
                name=userInfo.getEmail();
            }else {
                name=userInfo.getName();
            }
            //5.返回登录信息和token
            //token:
            // a)。按一定规则（JWT工具）生成的包含用户其它信息的字符串；
            // b)。有一定的生存时间
            //jwt生成token字符串
            if (userInfo != null) {
                token = JwtHelper.createToken(userInfo.getId(), name);
                //校验是否被禁用
                if(userInfo.getStatus() == 0) {
                    throw new AppointmentException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
                }
            }
        }
        userMap.put("name",name);
        userMap.put("token",token);
        return userMap;
    }

    @Override
    public UserInfo getByOpenid(String openid) {
        return baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid", openid));
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);
        //补充信息
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //更新
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, Map map) {
        //UserInfoQueryVo获取条件值
        String name = map==null?null:(String) map.get("name"); //用户名称
        Integer status = map==null?null:(Integer) map.get("status");//用户状态
        Integer authStatus = map==null?null:(Integer) map.get("authStatus"); //认证状态
        List<String> createTime= map==null?null:(List<String>) map.get("createTime"); //开始时间
        String createTimeBegin = createTime==null?null:createTime.get(0); //开始时间
        String createTimeEnd = createTime==null?null:createTime.get(1); //结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return pages;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void switchAuthStatus(Long userId, Integer switchAuth) {
        if(switchAuth.intValue()==2||switchAuth.intValue()==-1){
            UserInfo byId = this.getById(userId);
            byId.setAuthStatus(switchAuth);
            this.updateById(byId);
        }
    }

    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
